package com.thkj.modules.check.controller;

import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;

import com.thkj.common.util.PushUtils;
import com.thkj.common.util.RequestUtil;
import com.thkj.common.util.RmUtil;
import com.thkj.modules.check.entity.TblCheck;
import com.thkj.modules.check.service.TblCheckService;
import com.thkj.modules.user.entity.TblIndividual;
import com.thkj.modules.user.entity.TblSecurityAdmin;
import com.thkj.modules.user.service.TblIndividualService;
import com.thkj.modules.user.service.TblSecurityAdminService;

import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
import dp.R;
import dp.dao.PagingList;
import dp.web.BaseAction;

/**
 * 检查
 */
@RestController
@RequestMapping("/backstage/check")
public class CheckAction extends BaseAction {
	@Autowired
	TblCheckService tblCheckService;

	@Autowired
	TblIndividualService tblIndividualService;
	@Autowired
	TblSecurityAdminService tblSecurityAdminService;

	@RequestMapping("")
	public ModelAndView index() {
		return new ModelAndView("check/list");
	}

	@RequestMapping("/query")
	public R query(HttpServletRequest request, int page, int size) {
		Map<String, Object> param = RequestUtil.getParameterMap(request);
		if (!RmUtil.isAdmin(RmUtil.getLoginUser(request)) && !"true".equals(request.getParameter("onlyOwn"))) {
			param.put("userId", RmUtil.getLoginUser(request).getUserId());
		}
		PagingList<Map> list = tblCheckService.query(page, size, param);
		return R.success(list);
	}

	@RequestMapping("/edit")
	public R edit(HttpServletRequest request, TblCheck check) {
		try {
			if (StrUtil.isBlank(check.getId())) {
				check.setId(IdUtil.objectId());
				check.setUserId(RmUtil.getLoginUser(request).getUserId());
				tblCheckService.insertTblCheck(check);
				try {
					TblIndividual individual = tblIndividualService.getTblIndividualById(check.getIndividualId());
					TblSecurityAdmin securityAdmin = tblSecurityAdminService
							.getTblSecurityAdminById(individual.getUserId());
					if (individual != null && securityAdmin != null) {
						PushUtils.sendCheckMsg(securityAdmin.getRegistrationId(), "jy", check);
					}
				} catch (Exception e) {
				}
			} else {
				tblCheckService.updateTblCheck(check);
			}

			return R.SUCCESS;
		} catch (Exception e) {
			return R.failure(e.getMessage());
		}
	}

	@RequestMapping("/delete")
	public R delete(String id) {
		tblCheckService.deleteTblCheck(id);
		return R.SUCCESS;
	}

	/**
	 * 审核---
	 *
	 * @param check
	 * @return
	 */
	@RequestMapping("/pass")
	public R pass(TblCheck check) {
		check.setResult("1");
		tblCheckService.updateResult(check);
		return R.SUCCESS;
	}
}